package com.itheima.health.service.impl;

import com.itheima.health.common.CookieConstant;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.PasswordConstant;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.dto.LoginDTO;
import com.itheima.health.pojo.dto.MemberLoginDTO;
import com.itheima.health.pojo.entity.Member;
import com.itheima.health.service.LoginService;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.time.LocalDate;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private HttpServletResponse response;

    /**
     * 手机模块-用户手机登录
     * @param dto
     *
     */
    @Override
    public void smsLogin( MemberLoginDTO dto) {
        String code = (String) redisTemplate.opsForValue().get(RedisConst.LOGIN_VALIDATE_CODE_PREFIX+dto.getTelephone());
        if (!dto.getValidateCode().equals(code)) {
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }
        Member member;
        synchronized (this) {
            member = memberDao.selectMemberByTelephone(dto.getTelephone());
            if (member == null) {
                member =Member.builder()
                        .phoneNumber(dto.getTelephone())
                        .regTime(Date.valueOf(LocalDate.now()))
                        .password(PasswordConstant.DEFAULT_PASSWORD).build();
                memberDao.add(member);
            }
        }
        Cookie cookie = new Cookie(CookieConstant.LOGIN_AUTH,member.getId().toString());
        cookie.setPath("/");
        cookie.setMaxAge(360000000);
        response.addCookie(cookie);
    }
}
